
package com.ruhua.java.service;

import com.ruhua.java.dao.Article;
import com.ruhua.java.dto.ArticleDTO;
import com.ruhua.java.exception.NotFoundException;
import com.ruhua.java.exception.TrowException;
import com.ruhua.java.repository.ArticleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;


@Service
public class ArticleService {
    @Autowired
    ArticleRepository articleRepository;

    public Article getById(Long num) {
        Article article = articleRepository.findOneById(num);
        if(article == null){
            throw new NotFoundException(10001);
        }
        return article;
    }


    public List<Article> getArticleList() {
        return this.articleRepository.findAll();
    }


    public void createItem(ArticleDTO articleDTO) {
        Article item = Article.builder()
                .title(articleDTO.getTitle())
                .content(articleDTO.getContent())
                .type(articleDTO.getType())
                .image(articleDTO.getImage())
                .build();
        articleRepository.save(item);
    }

    public void updateItem(ArticleDTO dto) {
        Article item = this.getById(dto.getId());
        item.setTitle(dto.getTitle());
        item.setImage(dto.getImage());
        item.setType(dto.getType());
        item.setContent(dto.getContent());
        articleRepository.save(item);
    }

    public void delItem(Long id) {
        try {
            articleRepository.deleteById(id);
        } catch (Exception e) {
            throw new NotFoundException(10001);
        }
    }
}
